import os.path

from elixir import *
from datetime import datetime, date

metadata.bind = "sqlite:///notes.sqlite"
#metadata.bind.echo = True

def initialize_and_upgrade():
    if os.path.exists("./notes.sqlite"):
        # Upgrade if needed
        setup_all()
    else:
        setup_all(True)

        c = Category()
        c.name = "Unfiled"
        c.description = "Notes not associated with a category."
        persist()

def persist():
    session.commit()

class Link(Entity):
    using_options(tablename='Links')

    id = Field(Integer, primary_key = True)
    phrase = Field(Text())
    url = Field(Text())
    Note = ManyToOne('Note')

    def __init__(self, phrase, url):
        self.phrase = phrase
        self.url = url

    def __repr__(self):
        return self.phrase + ': ' + self.url

    @staticmethod
    def check_phrase_is_linked(phr):
        return Link.query.filter_by(phrase = phr) != None

    @staticmethod
    def get_link_by_phrase(phr):
        return Link.query.filter_by(phrase = phr).first()

class Note(Entity):
    using_options(tablename='Notes')

    id = Field(Integer, primary_key = True)
    content = Field(Text())
    summary = Field(Text(256), unique = True)
    create_date = Field(Date)
    update_time = Field(DateTime)
    categories = ManyToMany('Category', tablename='CategoriesNotes')
    links = OneToMany('Link')

    def __init__(self):
        self.create_date = date.today()
        self.update_time = datetime.now()

    def __repr__(self):
        return self.summary

    @staticmethod
    def get_notes_by_date(dt_tuple):
        year, month, day = dt_tuple
        month += 1
        dt_tuple = (year, month, day)
        dt = date(*dt_tuple)
        return Note.query.filter_by(create_date=dt).all()

    @staticmethod
    def get_note_by_id(nid):
        return Note.query.filter_by(id=nid).first()

class Category(Entity):
    using_options(tablename='Categories')

    id = Field(Integer, primary_key = True)
    name = Field(Text(256), unique = True)
    description = Field(Text(1024))
    create_date = Field(Date)
    notes = ManyToMany('Note', tablename='CategoriesNotes')

    def __init__(self):
        self.create_date = date.today()

    def __repr__(self):
        return self.name

    @staticmethod
    def get_category(n):
        return Category.query.filter_by(name=n).one()
